Skip to main content

Invert Binary Tree

Question

How can I invert a binary tree such that the left and right subtrees of each node are swapped?

Example 1
Input: 
4
/ \
2 7
/ \ / \
1 3 6 9

Output:
4
/ \
7 2
/ \ / \
9 6 3 1

Solution

all//Invert Binary Tree.py


# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def invertTree(self, root):
if root == None:
return None
else:
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return root